﻿@page "/test"
@using System.Reflection.Metadata
@using Microsoft.AspNetCore.SignalR.Client
@using System.Text
@using TrackSystem.Entities.Dtos.Var
@using TrackSystem.IO.Utils
@using TrackSystem.UI.Server.HttpRepository.Logic
@using TrackSystem.UI.Server.HttpRepository.Var
@using Console = System.Console

@inject NavigationManager NavigationManager
@inject IJSRuntime JSRuntime

<h3>表达式测试</h3>

<Divider />

<div class="row col-12">
    <textarea id="expressid"
              @onblur="OnCondClick"
              type="text" class="form-control"
              rows="4"
              @bind="@content">
    </textarea>
</div>

<br />

<div class="row">
    <div class="col-4">
        <Dropdown TValue="string"
                  Items="NameItems"
                  OnSelectedItemChanged="OnRegNameChanged"
                  Color="Color.Secondary">
        </Dropdown>
    </div>

    <div class="col-4">
        <Button class="btn btn-info" OnClick="@ClaculateVar">计算变量</Button>
    </div>

    <div class="col-4">
        <Button class="btn btn-primary" OnClick="@ClaculateLogic">计算表达式</Button>
    </div>
</div>


<Divider />

<div class="row">
    <p>@clacResult</p>
</div>

@code {
    private string content { get; set; } = "";
    private string clacResult { get; set; } = "";
    private string regName = "";


    private List<SelectedItem> NameItems { get; set; } = new();
    private List<string> NameList = new();

    [Inject]
    public IVarHttpRepository? varRepo { get; set; }

    [Inject]
    public ILogicHttpRepository? logicRepo { get; set;  }

    private HubConnection hubConnection;

    /// <summary>
    /// 页面初始化
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        if (varRepo == null || logicRepo == null)
        {
            clacResult = "后台系统不存在";
            return;
        }

        IEnumerable<VarDto> result = await varRepo.GetAll();
        NameItems = result.Select(c => new SelectedItem(c.Name, c.Name + "|" + c.DataType.ToString())).ToList();
        //NameList = result.Select(c => $"{c.Name}|{c.DataType}").ToList();
    }



    /// <summary>
    /// 测试表达式是否正确
    /// </summary>
    /// <returns></returns>
    private async Task ClaculateVar()
    {
        if (varRepo == null)
        {
            clacResult = "后台系统不存在";
            return;
        }

        FormulaResult result = await varRepo.TestForula(content);
        if (result == null)
        {
            clacResult = "计算错误";
            return;
        }

        clacResult = result.Message ??= "";
    }

    /// <summary>
    /// 选择项是否改变
    /// </summary>
    /// <param name="item">选择的项目</param>
    /// <returns></returns>
    private Task OnRegNameChanged(SelectedItem selectItem)
    {
        var regName = " " + selectItem.Text.Split('|')[0] + " ";
        content = HandleStringInsert(content, condCursorStart, condCursorEnd, regName);
        condCursorStart += regName.Length;
        condCursorEnd = condCursorStart;
        StateHasChanged();
        return Task.CompletedTask;
    }

    private async Task ClaculateLogic()
    {
        if (logicRepo == null)
        {
            clacResult = "后台系统不存在";
            return;
        }

        var result = await logicRepo.TestForula(content);
        clacResult = $"{result.Success} : { result.Message}";
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            try
            {
                // 建立SIGNALR连接
                hubConnection = new HubConnectionBuilder()
                    .WithUrl("http://localhost:5000/trackhub")
                    .WithAutomaticReconnect([TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3)])
                    .Build();

                // 发送请求
                hubConnection.On<List<string>>("RecvVarNames", (tt) =>
                {
                    NameList = tt;
                    clacResult = "SignalR success!";
                    InvokeAsync(StateHasChanged);
                });

                await hubConnection.StartAsync();
                await hubConnection.SendAsync("GetVarNames");
            }
            catch (Exception e)
            {
                clacResult = e.Message;
            }
        }
    }

    private int condCursorStart = 0;
    private int condCursorEnd = 0;

    private async Task OnCondClick()
    {
        condCursorStart = await JSRuntime.InvokeAsync<int>(
            "eval",
            "document.getElementById('expressid').selectionStart");

        condCursorEnd = await JSRuntime.InvokeAsync<int>(
                "eval",
                "document.getElementById('expressid').selectionEnd");
        Console.WriteLine($"condCursorStart: {condCursorStart}, condCursorEnd: {condCursorEnd}");
    }


    /// <summary>
    /// 将regName插入到字符串中
    /// </summary>
    /// <param name="source">目标字符串</param>
    /// <param name="start">起始位置</param>
    /// <param name="end">结束位置</param>
    /// <param name="s">插入的字符串</param>
    /// <returns></returns>
    private string HandleStringInsert(string source, int start, int end, string s)
    {
        int sourceLength = source.Length;
        if (start < 0 || start >= sourceLength)
        {
            start = (sourceLength == 0 ? 0 : sourceLength);
        }
        if (end < 0 || end >= sourceLength)
        {
            end = (sourceLength == 0 ? 0 : sourceLength);
        }
        var sb = new StringBuilder(source);
        sb.Remove(start, end - start);
        sb.Insert(start, s);
        return sb.ToString();
    }
}


<style>
    /* 添加下拉菜单容器滚动条 */
    .dropdown-menu {
        max-height: 200px; /* 限制最大高度 */
        overflow-y: auto; /* 垂直滚动条 */
        scrollbar-width: thin; /* 细滚动条样式 */
    }

        /* 滚动条美化（可选）*/
        .dropdown-menu::-webkit-scrollbar {
            width: 6px;
        }

        .dropdown-menu::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 3px;
        }
</style>
